// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.components.table;

import java.util.ArrayList;
import java.util.List;

import lichen.pages.base.ITablePage;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.corelib.components.Loop;
import org.apache.tapestry5.ioc.annotations.Inject;

/**
 * 一个类似T4中TablePages的分页组件
 * 
 * @author <a href=mailto:Ghostbb@bjmaxinfo.com>Ghostbb</a>
 * @version $Revision$
 * @since 0.0.3
 */
public class TablePages {
	
	@Inject
	private ComponentResources componentResources;
	
	/**
	 * 得到topic数量
	 * @return
	 * @since 0.0.3
	 */
	@Parameter(value="0")
	private long totalRowCount;
	
	/**
	 * 每页显示的行数，默认为10
	 */
	@Parameter(value="10")
	private int nPageSize;
	
	/**
	 * 分页时页码使用的循环组件
	 */
	@Component(parameters = { "source=pageNums", "value=pageIndex" })
	private Loop splitPageLoop;
	
	/**
	 * 循环显示使用的页码
	 */
	private int pageIndex;
	
	/**
	 * 得到页数
	 * @return
	 * @since 0.0.3
	 */
	public List getPageNums(){
		long totalCount = this.totalRowCount;
		long totalPage = 0;
		if(totalCount%nPageSize==0){
			totalPage = totalCount/nPageSize;
		} else{
			totalPage = totalCount/nPageSize+1;
		}
		List pageNumList = new ArrayList();
		if(totalPage == 0){
			pageNumList.add(1);
		} else{
			for(int i=1;i<=totalPage;i++){
				pageNumList.add(i);
			}
		}
		return pageNumList;
	}
	
	/**
	 * 翻页的链接
	 */
	public ITablePage onActionFromSplitPage(long pageNum){
		ITablePage page = (ITablePage)componentResources.getPage();
		page.setNFirst((int)((pageNum-1)*nPageSize));
		page.setNPageSize(this.nPageSize);
		return page;
	}

	/**
	 * @return Returns the pageIndex.
	 */
	public int getPageIndex() {
		return pageIndex;
	}

	/**
	 * @param pageIndex The pageIndex to set.
	 */
	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

	/**
	 * @return Returns the totalRowCount.
	 */
	public long getTotalRowCount() {
		return totalRowCount;
	}

	/**
	 * @param totalRowCount The totalRowCount to set.
	 */
	public void setTotalRowCount(long totalRowCount) {
		this.totalRowCount = totalRowCount;
	}

	/**
	 * @return Returns the nPageSize.
	 */
	public int getNPageSize() {
		return nPageSize;
	}

	/**
	 * @param pageSize The nPageSize to set.
	 */
	public void setNPageSize(int pageSize) {
		nPageSize = pageSize;
	}
}
